function buildHeap(arr, len) {
    for (let i = Math.floor(len / 2); i > 0; i--) {
        heapify(arr, i, len)
    }
}
function swap(arr, i, j) {
    let temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}
// 向下调整
function heapify(arr, i, len) {
    while (true) {
        let minIndex = i
        if (2 * i <= len && arr[2 * i] < arr[i]) {
            minIndex = 2 * i
        }
        if (2 * i + 1 <= len && arr[2 * i + 1] < arr[minIndex]) {
            minIndex = 2 * i + 1
        }
        if (minIndex !== i) {
            swap(minIndex, i, arr)
            i = minIndex
        } else break;
    }
}
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findKthLargest = function (nums, k) {
    const heap = [null]
    for (let i = 0; i < nums.length; i++) {
        if (i < k) {
            heap.push(nums[i])
            if (i === k - 1) buildHeap(heap, k)
        } else {
            if(nums[k] > heap[1]) {
                heap[1] = nums[k]
                heapify(heap, 1, k)
            }
        }
    }
    return heap[1]
};